#include "graphjudger.h"
#include "line.h"
#include "point.h"

GraphJudger::GraphJudger()
{
}

QLinkedList<QPointF> GraphJudger::findCrossingPoint(const QLinkedList<Line *> &ll)
{
//    QPointF* starts = new QPointF[ll.size()];
//    QPointF* ends = new QPointF[ll.size()];
    QLineF *lines = new QLineF[ll.size()];

    QLinkedList<Line*>::const_iterator it;
    int i, j;
    for (i=0, it=ll.begin(); it!=ll.end(); i++, it++)
    {
        Line *line = *it;
        QPointF start = line->getStartPoint()->rect().center();
        QPointF end = line->getEndPoint()==NULL ?
                    QPointF() : line->getEndPoint()->rect().center();
        lines[i] = QLineF(start, end);
    }
    QLinkedList<QPointF> crossingPoints;
    for (i=0; i<ll.size(); i++)
        for (j=i+1; j<ll.size(); j++)
        {
            QPointF crossPoint;
            if (lines[i].intersect(lines[j], &crossPoint)==QLineF::BoundedIntersection)
            {
                if (!areSamePoint(crossPoint, lines[i].p1()) &&
                        !areSamePoint(crossPoint, lines[i].p2()) &&
                        !areSamePoint(crossPoint, lines[j].p1()) &&
                        !areSamePoint(crossPoint, lines[j].p2()))
                    crossingPoints.push_back(crossPoint);
            }
        }

    delete lines;
    return crossingPoints;
}

bool GraphJudger::areSamePoint(const QPointF &p1, const QPointF &p2)
{
    qreal dx = p1.x()>p2.x() ? p1.x()-p2.x() : p2.x()-p1.x();
    qreal dy = p1.y()>p2.y() ? p1.y()-p2.y() : p2.y()-p1.y();
    if (dx < 0.000001 && dy < 0.000001)
        return true;
    else return false;
}


